import curses, curses.textpad, curses.ascii
import sys, re
import processor

text = []

def refreshline():
    screen.hline(textboxrow-1, 1, curses.ACS_HLINE, columns-2)

def rowcount(entry):
    return int(len(entry[0])/columns) + int(len(entry[1])/columns) + 2

def addtext(command, response):
    text.append((command, response))
    outwin.clear()
    pos = 0
    entriesToPrint = []
    length = 0
    for a in xrange(len(text)-1, -1, -1):
        c = rowcount(text[a])
        if length + c > outwin.getmaxyx()[0]-2: break
        length = length + c
        entriesToPrint.insert(0, text[a])
    for command, response in entriesToPrint:
        outwin.addstr(pos, 0, command)
        pos = pos + int(len(command)/columns) + 1
        outwin.addstr(pos, 0, response, curses.A_BOLD)
        pos = pos + int(len(response)/columns) + 1
    outwin.refresh()
    refreshline()

def updatestatus():
    screen.addstr(0, 0, " " * columns, curses.A_REVERSE)
    screen.addstr(0, 0, "Living Room", curses.A_REVERSE)

def validator(c):
    if c == curses.ascii.NL:
        return curses.ascii.BEL
    else:
        return c

def init(scr):
    global game, screen, rows, columns, textboxrow
    global outwin, textpad
    screen = scr
    rows, columns = screen.getmaxyx()
    textboxrow = rows - 3
    outwin = screen.subwin(textboxrow-1, columns-2, 2, 1)
    refreshline()
    textpadwin = screen.subwin(rows-textboxrow-1, columns-2, textboxrow, 1)
    textpad = curses.textpad.Textbox(textpadwin)
    game = __import__(sys.argv[1])
    addtext("", game.processor.init())
    while 1:
        updatestatus()
        screen.refresh()
        textpadwin.clear()
        text = textpad.edit(validator).strip()
        if not re.search("^(quit|exit)$", text):
            ret = game.processor.process(text)
            if ret: addtext(text, ret)
        else:
            addtext(text, "Goodbye.")
            break
    screen.refresh()

curses.wrapper(init)
